package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 通用接口
 * @author
 * @date 2021/1/18 9:09 下午
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {
    private final AliOssProperties aliOssProperties;
    private final AliOssUtil aliOssUtil;

    public CommonController(AliOssProperties aliOssProperties, AliOssUtil aliOssUtil) {
        this.aliOssProperties = aliOssProperties;
        this.aliOssUtil = aliOssUtil;
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
     log.info("文件上传：{}",file);
     try {
         //获取原始文件名
         String originalFilename = file.getOriginalFilename();
         //获取原始文件后缀  dfdfdf.png
         String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
         //构造新文件名称
         String ObjectName = UUID.randomUUID().toString()+extension;
         //文件请求路径
         String filePath=aliOssUtil.upload(file.getBytes(),ObjectName);
         return Result.success(filePath);
         //上传文件
         //TODO:将上传的文件保存到服务器的磁盘
         //TODO:将上传的文件保存到OSS服务器
     }catch (IOException e){
         log.error("文件上传失败：{}",e);
     }
     return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
